
(function ($) {

	$.fn.rssfeed = function (url, options, fn) {

		// Set pluign defaults
		var defaults = {
			limit: 10,
			header: true,
			titletag: 'h4',
			date: true,
			content: true,
			snippet: true,
			media: true,
			showerror: true,
			errormsg: '',
			key: null,
			ssl: false,
			linktarget: '_blank'
		};
		var options = $.extend(defaults, options);

		// Functions
		return this.each(function (i, e) {
			var $e = $(e);
			var s = '';

			// Check for SSL protocol
			if (options.ssl) s = 's';

			// Add feed class to user div
			if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');

			// Check for valid url
			if (url == null) return false;

			// Create Google Feed API address
			var api = "http" + s + "://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + encodeURIComponent(url);
			if (options.limit != null) api += "&num=" + options.limit;
			if (options.key != null) api += "&key=" + options.key;
			api += "&output=json_xml"

			// Send request
			$.getJSON(api, function (data) {

				// Check for error
				if (data.responseStatus == 200) {

					// Process the feeds
					_process(e, data.responseData, options);

					// Optional user callback function
					if ($.isFunction(fn)) fn.call(this, $e);

				} else {

					// Handle error if required
					if (options.showerror)
						if (options.errormsg != '') {
							var msg = options.errormsg;
						} else {
							var msg = data.responseDetails;
						};
					$(e).html('<div class="rssError"><p>' + msg + '<br/>' + api + '</p></div>');
				};
			});
		});
	};

	// Function to create HTML result
	var _process = function (e, data, options) {

		// Get JSON feed data
		var feeds = data.feed;
		if (!feeds) {
			return false;
		}
		var html = '';
		var row = 'odd';

		// Get XML data for media (parseXML not used as requires 1.5+)
		if (options.media) {
			var xml = getXMLDocument(data.xmlString);
			var xmlEntries = xml.getElementsByTagName('item');
		}

		// Add header if required
		if (options.header)
			html += '<div class="site">' +
				'<p><b>' + feeds.title + '</b><br/>' + feeds.description + '</p>' +
				'<div class="layer">' + '<span><a href="' + feeds.feedUrl + '">' +
				'<img src="http://cdn.pbdesk.com/images/social/rss_blue.png" alt="more..." height="33" width="33"></a></span></div>';



		// Add body
		html += '<div class="portfolio_image">' +
			'<ul class="resourcelist">';

		// Add feeds
		for (var i = 0; i < feeds.entries.length; i++) {

			// Get individual feed
			var entry = feeds.entries[i];
			var pubDate;

			// Format published date
			if (entry.publishedDate) {
				var entryDate = new Date(entry.publishedDate);
				var pubDate = entryDate.toDateString() + ' ' + entryDate.toLocaleTimeString();
			}

			var imageHtml = '';
			//media
			if (entry.mediaGroups) {
				var mediaElement = entry.mediaGroups[0];
				if (mediaElement && mediaElement.contents) {
					var mediaContent = mediaElement.contents[0];
					if (mediaContent) {
						imageHtml = '<img height="50px" width="70px" src="' + mediaContent.url + '" alt="' + mediaContent.texts[0].content + '" />';
					}
				}
			}
			if (imageHtml == '') {
				if (options.media && xmlEntries.length > 0) {
					var xmlMedia = xmlEntries[i].getElementsByTagName('enclosure');
					if (xmlMedia.length > 0) {
						for (var m = 0; m < xmlMedia.length; m++) {
							var xmlUrl = xmlMedia[m].getAttribute("url");
							var xmlType = xmlMedia[m].getAttribute("type");
							var xmlSize = xmlMedia[m].getAttribute("length");
							if (xmlType == "image/png" || xmlType == "image/jpg" || xmlType == "image/jpeg" || xmlType == "image/gif") {
								imageHtml = '<img height="50px" width="70px" src="' + xmlUrl + '" alt="' + entry.title + '" />';
							}
						}
					}
				}
			}
			if (imageHtml == '') {
				imageHtml = '<img height="50px" width="70px" src="http://cdn.pbdesk.com/images/icons/news64.png" alt="' + entry.title + '" />';
			}

			// Add feed row
			html += '<li style="background:none" class="rssRow ' + row + '">' +
				'<' + options.titletag + '><a  href="' + entry.link + '" title="View this feed at ' + feeds.title + '">' + entry.title + '</a></' + options.titletag + '>'
			//if (options.date && pubDate) html += 
			if (options.content) {

				// Use feed snippet if available and optioned
				if (options.snippet && entry.contentSnippet != '') {
					var content = entry.contentSnippet;
				} else {
					var content = entry.content;
				}

				html += '<div style="min-height: 50px;"><div style="float:left; padding-right:7px;">' + imageHtml + '</div>' + '<div style="float:right">' + pubDate + '</div><br/>' + content + '</div>'


			}
			html += '</li>';



			// Alternate row classes
			if (row == 'odd') {
				row = 'even';
			} else {
				row = 'odd';
			}
		}

		html += '</ul>' +
			'</div>'

		$(e).html(html);

		// Apply target to links
		$('a', e).attr('target', options.linktarget);
	};

	function formatFilesize(bytes) {
		var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
		var e = Math.floor(Math.log(bytes) / Math.log(1024));
		return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2) + " " + s[e];
	}

	function getXMLDocument(string) {
		var browser = navigator.appName;
		var xml;
		if (browser == 'Microsoft Internet Explorer') {
			xml = new ActiveXObject('Microsoft.XMLDOM');
			xml.async = 'false'
			xml.loadXML(string);
		} else {
			xml = (new DOMParser()).parseFromString(string, 'text/xml');
		}
		return xml;
	}

})(jQuery);
